<template>
  <div class="register-container">
    <div class="register-wrapper">
      <!-- 左侧品牌展示区（仅PC端显示） -->
      <div class="brand-section">
        <div class="brand-content">
          <h1 class="brand-title">医联智导</h1>
          <p class="brand-slogan">智能导诊，让就医更简单</p>
          <div class="brand-image">
            <svg width="200" height="200" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <circle cx="12" cy="6" r="4" stroke="#1989fa" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
              <path d="M8.5 18c0-2.5 1-4.5 2.5-5.5c1.5-1 3.5-1 6 0l0 0c2 1 3 3 3 5.5" stroke="#1989fa" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
              <path d="M16 21v-3.5c0-1-.5-2-1.5-2.5s-2 .5-3 1.5c-1-1-1.5-1.5-3-1.5s-1.5 1.5-1.5 2.5v3.5" stroke="#1989fa" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
              <path d="M6 13c0-1 1-2 2-2s2 1 2 2" stroke="#1989fa" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
              <path d="M16 13c0-1-1-2-2-2s-2 1-2 2" stroke="#1989fa" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </div>
        </div>
      </div>
      
      <!-- 右侧注册表单 -->
      <div class="form-section">
        <div class="form-content">
          <div class="form-header">
            <h2>注册</h2>
            <p>欢迎加入医联智导平台</p>
          </div>
          
          <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules" class="register-form">
            <!-- 手机号输入 -->
            <el-form-item prop="phone">
              <el-input
                v-model="registerForm.phone"
                placeholder="请输入手机号"
                :prefix-icon="Phone"
                :disabled="isLoading"
                clearable
              />
            </el-form-item>
            
            <!-- 验证码输入 -->
            <el-form-item prop="code">
              <el-input
                v-model="registerForm.code"
                placeholder="请输入验证码"
                :prefix-icon="Message"
                :disabled="isLoading || countdown > 0"
                clearable
              >
                <template #suffix>
                  <el-button
                    :disabled="!registerForm.phone || isLoading || countdown > 0"
                    type="text"
                    @click="getVerificationCode"
                    class="get-code-btn"
                  >
                    {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
            
            <!-- 密码输入 -->
            <el-form-item prop="password">
              <el-input
                v-model="registerForm.password"
                type="password"
                placeholder="请设置密码（8-20位，包含字母和数字）"
                :prefix-icon="Lock"
                :show-password="showPassword"
                @click:prefix="togglePasswordVisibility"
                :disabled="isLoading"
                clearable
              />
              
              <!-- 密码强度指示器 -->
              <div v-if="registerForm.password" class="password-strength">
                <div class="strength-indicators">
                  <div
                    v-for="(level, index) in 3"
                    :key="index"
                    class="strength-indicator"
                    :class="{
                      'weak': passwordStrength >= 1 && level === 1,
                      'medium': passwordStrength >= 2 && level === 2,
                      'strong': passwordStrength >= 3 && level === 3
                    }"
                  />
                </div>
                <span class="strength-text">
                  {{ passwordStrengthText }}
                </span>
              </div>
            </el-form-item>
            
            <!-- 确认密码 -->
            <el-form-item prop="confirmPassword">
              <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="请再次输入密码"
                :prefix-icon="Lock"
                :show-password="showConfirmPassword"
                @click:prefix="toggleConfirmPasswordVisibility"
                :disabled="isLoading"
                clearable
              />
            </el-form-item>
            
            <!-- 协议同意 -->
            <el-form-item prop="agreement">
              <el-checkbox v-model="registerForm.agreement" size="large">
                我已阅读并同意
                <el-link type="primary" @click="showUserAgreement">《用户协议》</el-link>
                和
                <el-link type="primary" @click="showPrivacyPolicy">《隐私政策》</el-link>
              </el-checkbox>
            </el-form-item>
            
            <!-- 错误提示 -->
            <div v-if="error" class="error-message">
              <el-icon><Warning /></el-icon>
              <span>{{ error }}</span>
            </div>
            
            <!-- 注册按钮 -->
            <el-form-item>
              <el-button
                type="primary"
                class="register-btn"
                :loading="isLoading"
                @click="handleRegister"
                :disabled="isLoading"
              >
                注册
              </el-button>
            </el-form-item>
            
            <!-- 已有账号 -->
            <div class="login-link">
              已有账号？
              <el-link type="primary" @click="goToLogin">立即登录</el-link>
            </div>
          </el-form>
        </div>
      </div>
    </div>
    
    <!-- 用户协议弹窗 -->
    <el-dialog v-model="agreementVisible" title="用户协议" width="600px">
      <div class="agreement-content">
        <h3>医联智导平台用户协议</h3>
        <p class="agreement-date">更新日期：2024年1月1日</p>
        <div class="agreement-text">
          <p>欢迎您使用医联智导平台服务。请您仔细阅读本协议内容，特别是加粗或下划线标注的条款，这些条款可能会明确您应履行的义务或对您的权利有所限制。</p>
          
          <h4>一、服务内容</h4>
          <p>医联智导平台提供智能导诊、科室推荐、病历管理等服务，旨在帮助用户更便捷地获取医疗信息和服务。</p>
          
          <h4>二、用户注册与账户安全</h4>
          <p>1. 用户在注册时应提供真实、准确、完整的个人资料，并保持资料的及时更新。</p>
          <p>2. 用户应妥善保管账户及密码信息，因账户或密码保管不善导致的损失由用户自行承担。</p>
          
          <h4>三、用户行为规范</h4>
          <p>用户不得利用本平台从事任何违法违规活动，包括但不限于传播虚假信息、干扰平台正常运行等。</p>
          
          <h4>四、知识产权</h4>
          <p>医联智导平台所有内容的知识产权归医联智导平台所有，未经授权，用户不得复制、修改或传播。</p>
          
          <h4>五、免责声明</h4>
          <p>平台提供的信息仅供参考，不构成医疗建议。用户应根据实际情况咨询专业医生的意见。</p>
        </div>
      </div>
    </el-dialog>
    
    <!-- 隐私政策弹窗 -->
    <el-dialog v-model="privacyVisible" title="隐私政策" width="600px">
      <div class="agreement-content">
        <h3>医联智导平台隐私政策</h3>
        <p class="agreement-date">更新日期：2024年1月1日</p>
        <div class="agreement-text">
          <p>医联智导平台非常重视用户隐私保护，我们将严格遵守法律法规，采取安全措施保护您的个人信息。</p>
          
          <h4>一、信息收集</h4>
          <p>我们可能收集您的姓名、手机号、症状描述等信息，用于提供导诊服务和病历管理。</p>
          
          <h4>二、信息使用</h4>
          <p>我们仅在提供服务的必要范围内使用您的信息，未经您的同意，不会向第三方分享您的个人信息。</p>
          
          <h4>三、信息保护</h4>
          <p>我们采取加密、访问控制等安全措施保护您的信息，防止信息泄露、篡改或丢失。</p>
          
          <h4>四、您的权利</h4>
          <p>您有权访问、更正或删除您的个人信息，也可以随时注销您的账户。</p>
          
          <h4>五、政策更新</h4>
          <p>我们可能会不时更新本隐私政策，更新后将在平台上公布，请您定期查看。</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watchEffect } from 'vue'
import { ElForm, ElFormItem, ElInput, ElButton, ElCheckbox, ElLink, ElDialog, ElMessage, ElIcon } from 'element-plus'
import { Phone, Lock, Message, Warning } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const registerFormRef = ref(null)
const registerForm = reactive({
  phone: '',
  code: '',
  password: '',
  confirmPassword: '',
  agreement: false
})
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const countdown = ref(0)
const isLoading = computed(() => authStore.isLoading)
const error = computed(() => authStore.error)
const passwordStrength = ref(0)
const agreementVisible = ref(false)
const privacyVisible = ref(false)

// 密码强度文本
const passwordStrengthText = computed(() => {
  switch (passwordStrength.value) {
    case 1: return '弱'
    case 2: return '中'
    case 3: return '强'
    default: return ''
  }
})

// 表单验证规则
const registerRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '请输入6位数字验证码', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请设置密码', trigger: 'blur' },
    { min: 8, max: 20, message: '密码长度应在8-20位之间', trigger: 'blur' },
    { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,20}$/, message: '密码必须包含字母和数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  agreement: [
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请阅读并同意用户协议和隐私政策'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 处理注册
const handleRegister = async () => {
  try {
    await registerFormRef.value.validate()
    
    await authStore.register(registerForm.phone, registerForm.password, registerForm.code)
    
    ElMessage.success('注册成功')
    
    // 注册成功后跳转到首页
    router.push('/')
  } catch (err) {
    console.error('注册失败:', err)
    // 如果是表单验证失败，Element Plus会自动提示，这里只处理其他错误
    if (err.message && !err.message.includes('validator')) {
      ElMessage.error(err.message || '注册失败，请重试')
    }
  }
}

// 获取验证码
const getVerificationCode = async () => {
  try {
    // 验证手机号
    if (!registerForm.phone || !/^1[3-9]\d{9}$/.test(registerForm.phone)) {
      ElMessage.error('请输入正确的手机号')
      return
    }
    
    await authStore.getVerificationCode(registerForm.phone)
    ElMessage.success('验证码发送成功')
    
    // 开始倒计时
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (err) {
    console.error('发送验证码失败:', err)
    ElMessage.error('发送验证码失败，请重试')
  }
}

// 前往登录页面
const goToLogin = () => {
  router.push('/login')
}

// 切换密码可见性
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
}

const toggleConfirmPasswordVisibility = () => {
  showConfirmPassword.value = !showConfirmPassword.value
}

// 显示用户协议
const showUserAgreement = () => {
  agreementVisible.value = true
}

// 显示隐私政策
const showPrivacyPolicy = () => {
  privacyVisible.value = true
}

// 密码强度检测
const checkPasswordStrength = (password) => {
  let strength = 0
  
  // 长度检查
  if (password.length >= 8) strength++
  
  // 包含字母检查
  if (/[A-Za-z]/.test(password)) strength++
  
  // 包含数字检查
  if (/\d/.test(password)) strength++
  
  passwordStrength.value = strength
}

// 监听密码变化
watchEffect(() => {
  checkPasswordStrength(registerForm.password)
})

// 自动聚焦到手机号输入框
const focusPhoneInput = () => {
  setTimeout(() => {
    const phoneInput = document.querySelector('input[placeholder="请输入手机号"]')
    if (phoneInput) {
      phoneInput.focus()
    }
  }, 100)
}

// 组件挂载时自动聚焦
focusPhoneInput()
</script>

<style scoped>
.register-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.register-wrapper {
  display: flex;
  width: 100%;
  max-width: 1000px;
  background-color: #ffffff;
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

/* 左侧品牌展示区 */
.brand-section {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #1989fa 0%, #36cbcb 100%);
  padding: 60px;
  color: #ffffff;
  display: none;
}

/* PC端显示品牌区 */
@media (min-width: 768px) {
  .brand-section {
    display: flex;
  }
}

.brand-content {
  text-align: center;
}

.brand-title {
  font-size: 32px;
  font-weight: 700;
  margin-bottom: 16px;
}

.brand-slogan {
  font-size: 16px;
  opacity: 0.9;
  margin-bottom: 40px;
}

.brand-image {
  margin-top: 20px;
}

/* 右侧表单区 */
.form-section {
  flex: 1;
  padding: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.form-content {
  width: 100%;
  max-width: 350px;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
}

.form-header h2 {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #303133;
}

.form-header p {
  color: #606266;
  font-size: 14px;
}

.register-form {
  width: 100%;
}

.register-btn {
  width: 100%;
  font-size: 16px;
  padding: 10px;
}

.error-message {
  display: flex;
  align-items: center;
  color: #f56c6c;
  font-size: 13px;
  margin-bottom: 15px;
  padding: 8px 12px;
  background-color: #fef0f0;
  border-radius: 4px;
}

.error-message .el-icon {
  margin-right: 8px;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  color: #606266;
  font-size: 14px;
}

/* 密码强度指示器 */
.password-strength {
  margin-top: 8px;
}

.strength-indicators {
  display: flex;
  gap: 4px;
  margin-bottom: 4px;
}

.strength-indicator {
  flex: 1;
  height: 4px;
  background-color: #e4e7ed;
  border-radius: 2px;
}

.strength-indicator.weak {
  background-color: #f56c6c;
}

.strength-indicator.medium {
  background-color: #e6a23c;
}

.strength-indicator.strong {
  background-color: #67c23a;
}

.strength-text {
  font-size: 12px;
  color: #909399;
}

/* 协议弹窗内容 */
.agreement-content {
  max-height: 400px;
  overflow-y: auto;
}

.agreement-date {
  color: #909399;
  font-size: 14px;
  margin-bottom: 20px;
}

.agreement-text {
  line-height: 1.8;
  font-size: 14px;
  color: #606266;
}

.agreement-text h4 {
  margin-top: 20px;
  margin-bottom: 10px;
  color: #303133;
  font-size: 16px;
}

.agreement-text p {
  margin-bottom: 10px;
}

/* 响应式设计 */
@media (max-width: 767px) {
  .register-wrapper {
    width: 100%;
    height: 100vh;
    max-width: none;
    border-radius: 0;
    box-shadow: none;
  }
  
  .form-section {
    padding: 20px;
  }
  
  .form-content {
    max-width: 100%;
  }
}
</style>